/**
 * @description user services
 * @author 追哥
 */

const { User } = require('../db/model/index');
const { formatUser } = require('./_format');
/**
 *
 * @param {string} 用户名
 * @param {string} 密码
 */
async function getUserInfo(userName, password) {
    const whereOpt = {
        userName,
    };
    if (password) {
        whereOpt.password = password;
    }
    const result = await User.findOne({
        attributes: ['id', 'userName', 'nickName', 'picture', 'city', 'gender'],
        where: whereOpt,
    });
    if (result == null) {
        return result;
    }

    const formatRes = formatUser(result.dataValues);
    return formatRes;
}
/**
 *
 * @param {string} userName
 * @param {string} password
 * @param {number} gender  性别 1男 2女 3保密
 * @param {string} nickName 昵称
 */
async function createUser({ userName, gender = 3, password, nickName }) {
    const result = await User.create({
        userName,
        password,
        gender,
        nickName: nickName ? nickName : userName,
    });
    return result.dataValues;
}

async function deleteUser(userName) {
    const result = await User.destroy({
        where: {
            userName,
        },
    });
    return result > 0;
}

//更新用户信息
async function updateUser(
    { newPassword, newNickName, newCity, newPicture },
    { userName, password }
) {
    const updateData = {};
    newPassword && (updateData.password = newPassword);
    newNickName && (updateData.nickName = newNickName);
    newCity && (updateData.city = newCity);
    newPicture && (updateData.picture = newPicture);
    
    const whereData = {
        userName
    };
    password && (whereData.password = password);

    const result = await User.update(updateData,{where:whereData});
    return result[0] > 0;
}

module.exports = {
    getUserInfo,
    createUser,
    deleteUser,
    updateUser
};
